//状态对象
const state = {
    userId: localStorage.getItem('userId') || '',
    account: localStorage.getItem('account') || '',
    username: localStorage.getItem('username') || '',
}

//基于state的getter计算属性的对象
const getters = {
    // Filtering currentUser
    currentUser: state => {
        return {
            userId: state.userId,
            account: state.account,
            username: state.username
        }
    }
}

//更新state的多个方法的对象
const mutations = {
    updateUser(state, payload) {
        switch (payload.name) {
            case 'userId':
                state.userId = payload.value
                break
            case 'account':
                state.account = payload.value
                break
            case 'username':
                state.username = payload.name
                break
            default:
                console.log('Error:Dont directly mutate Vuex store')
        }
    },
    getUser(state) {
        state.userId = localStorage.getItem('userId');
        state.account = localStorage.getItem('account');
        state.username = localStorage.getItem('username');
    },
    setUser(state, payload) {
        localStorage.setItem('userId', payload.id);
        localStorage.setItem('account', payload.account);
        localStorage.setItem('username', payload.username);
        state.userId = payload.id;
        state.account = payload.account;
        state.username = payload.username;
    },
    logout(state) {
        localStorage.removeItem('token');
        localStorage.removeItem('userId');
        localStorage.removeItem('account');
        localStorage.removeItem('username');
        state.userId = '';
        state.account = '';
        state.username = '';
    }
}

//通过mutations间接更新state的多个方法的对象
const actions = {
    //同步记录用户信息
    setUser({commit}, user) {
        commit('setUser', user);
    },
    //同步清空缓存
    logout({commit, rootState}) {
        commit('logout');
    }
}

export default {
    state,
    getters,
    mutations,
    actions
}
